/**
 * Created by xiey on 2016/3/21.
 */
as.directive('aForm', [function () {
    return {
        restrict  : 'EA',
        scope     : {
            form  : '=?name',
            option: '<'
        },
        template  : function () {
            var content = [];
            content.push('<form name="$$form" ng-submit="form.submit()" novalidate class="form-horizontal">');
            content.push('  <a-field ng-repeat="field in option.fields track by $index" ng-model="values[field.name][field.name]" field="field"></a-field>');
            content.push('  <div class="btn btn-group"><button type="submit" class="btn">确认</button></div>');
            content.push('</form>');
            return content.join('');
        },
        controller: ['$scope', '$http', function ($scope, $http) {
            $scope.form = $scope.form || {};
            $scope.option.listeners = $scope.option.listeners || {};
            // 0:未提交; 1:正在提交中; 2:提交完成
            $scope.state = 0;
            $scope.option.listeners.before = $scope.option.listeners.before || angular.noop;
            $scope.option.listeners.after = $scope.option.listeners.after || angular.noop;
            $scope.values = {};
            var fieldsMap = {};
            $scope.option.fields.forEach(function (field) {
                field.type = field.type || 'text';
                $scope.values[field.name] = {};
                fieldsMap[field.name] = field;
                $scope.values[field.name][field.name] = undefined;
                if ($scope.option.data) {
                    $scope.values[field.name] = $scope.option.data[field.name];
                }
            });
            $scope._submit = function () {
                var formData = $scope.form.getFormData();
                $scope.state = 1;
                return $http.post($scope.option.api, formData).then(function (res) {
                    var result = res.data;
                    if (!result.success) {
                        angular.forEach(result.errors, function (v, k) {
                            var field = fieldsMap[k];
                            if (field) {
                                field.setError(v);
                            }
                        });
                    }
                }).finally(function () {
                    $scope.$$form.$setSubmitted();
                    $scope.state = 2;
                });
            };

            angular.extend($scope.form, {
                setFormData: function (data) {
                    if (!data) {
                        return;
                    }
                    for (var k in $scope.values) {
                        $scope.values[k][k] = data[k];
                    }
                },
                getFormData: function () {
                    var data = {};
                    for (var k in $scope.values) {
                        data[k] = $scope.values[k][k];
                    }
                    return angular.merge({}, data);
                },
                hasError   : function () {
                    return $scope.option.fields.some(function (field) {
                        field.checkError();
                        return field.hasError;
                    });
                },
                submit     : function () {
                    if ($scope.form.hasError()) {
                        return;
                    }
                    // 提交的数据
                    var formData = $scope.form.getFormData();
                    var after = $scope.option.listeners.before(formData);
                    // 判断after是返回的 undefined/false/true/promise对象
                    if (after === false) {
                        return;
                    }
                    // 返回的是 promise 对象
                    if (after && after.finally) {
                        after.finally(function () {
                            return $scope._submit();
                        }).then(function () {
                            $scope.option.listeners.after();
                        });
                    } else {
                        $scope._submit().finally(function () {
                            $scope.option.listeners.after();
                        });
                    }
                }
            });
        }]
    };
}]);